package com.xindaoapp.happypet.ui;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v4.widget.DrawerLayout;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.TranslateAnimation;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.activity.HomeBannerDetailActivity;
import com.xindaoapp.happypet.activity.MainActivity;
import com.xindaoapp.happypet.activity.Search2Activity;
import com.xindaoapp.happypet.adapter.XinDaoBaseAdapter;
import com.xindaoapp.happypet.application.HappyPetApplication;
import com.xindaoapp.happypet.bean.Groups;
import com.xindaoapp.happypet.bean.Groups.Group;
import com.xindaoapp.happypet.bean.HomeBanner;
import com.xindaoapp.happypet.bean.HomeBannerEntity;
import com.xindaoapp.happypet.bean.MainDatas;
import com.xindaoapp.happypet.bean.MainDatas.MainData;
import com.xindaoapp.happypet.fragments.ChangeCenterFragment;
import com.xindaoapp.happypet.utils.CommonParameter;
import com.xindaoapp.happypet.utils.CommonParameter.UserState;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.IRequest;
import com.xindaoapp.happypet.view.CircleImageView;
import com.xindaoapp.happypet.view.HomeGroupPager;
import com.xindaoapp.happypet.view.RollViewPager;
import com.xindaoapp.happypet.view.RoundImageView;
import com.xindaoapp.happypet.viewpager.homegroup.PagerWindow;

/**
 * 主页
 * 
 * @author Yomine
 */
public class MainFragment extends BaseFragment implements OnClickListener {

    public MainFragment() {
        super();
        // TODO Auto-generated constructor stub
    }

    private TextView mTitle;
    private ImageView mBackView, mRightview, mGroupLeft, mGroupRight;
    private PullToRefreshListView mlistview;
    /** 轮播图 */
    private LinearLayout mViewPager;
    private TextView mtvDescription;
    private LinearLayout mllPoints;

    private List<HomeBanner> mBanners;

    private View vFoot, vHeader;

    private RelativeLayout vTopbar;


    private boolean mFrist = true;

    private static int page = 1;
    private static int pagesize = 10;
    /** 下拉的状态 -1为第一次加载 0为加载 1为刷新 */
    private static int loadFist = -1;

    private static int total = 0;

    private TextView vDabang, vDaren, vNiuniu;

    private RelativeLayout xPagerRootView;



    /**
     * 首页推荐圈子
     */
    private HomeGroupPager viewpager;
    private int count;
    private int groupSize;
    private int currentPage;
    private boolean mIsNavigationOpen;

    private final ArrayList<PagerWindow> views = new ArrayList<PagerWindow>();

    private HomePagerAdapter homePagerAdapter;
    private View mBackToTop;
    private DrawerLayout mDrawerLayout;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        return mView = inflater.inflate(R.layout.fragment_main, container, false);
    }

    @SuppressWarnings("deprecation")
    @Override
    protected void initViews() {
        // vTopFrame = (FrameLayout) mView.findViewById(R.id.top_frame);

        mRightview = (ImageView) mView.findViewById(R.id.top_bar_right_imageview);

        mlistview = (PullToRefreshListView) mView.findViewById(R.id.listview);
        vTopbar = (RelativeLayout) mView.findViewById(R.id.top_bar);


        mDrawerLayout = (DrawerLayout) getActivity().findViewById(R.id.drawer_layout);

        mView.findViewById(R.id.top_bar_left_imageview).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // if (mIsNavigationOpen) {
                // mIsNavigationOpen = false;
                // mDrawerLayout.closeDrawer(Gravity.LEFT);
                // } else {
                // mIsNavigationOpen = true;
                mDrawerLayout.openDrawer(Gravity.LEFT);
                // }

            }
        });


        mlistview.setMode(Mode.PULL_FROM_START);
        LayoutInflater inflater =
                (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        vHeader = inflater.inflate(R.layout.xlistview_viewpage_main, null);
        vFoot = inflater.inflate(R.layout.layout_loading_footer, null);
        viewpager = (HomeGroupPager) vHeader.findViewById(R.id.viewpager);
        mViewPager = (LinearLayout) vHeader.findViewById(R.id.viewpager1);
        xPagerRootView = (RelativeLayout) vHeader.findViewById(R.id.xlistview_viewpage1);
        xPagerRootView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                CommonParameter.sScreenWidth * 248 / 640));



        mViewPager.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                CommonParameter.sScreenWidth * 248 / 640));

        mtvDescription = (TextView) vHeader.findViewById(R.id.tv_image_description1);
        mllPoints = (LinearLayout) vHeader.findViewById(R.id.ll_points1);
        vDaren = (TextView) vHeader.findViewById(R.id.daren);
        vDabang = (TextView) vHeader.findViewById(R.id.dabang);
        vNiuniu = (TextView) vHeader.findViewById(R.id.niuniu);

        mGroupLeft = (ImageView) vHeader.findViewById(R.id.group_left);
        mGroupRight = (ImageView) vHeader.findViewById(R.id.group_right);

        mGroupLeft.setVisibility(View.INVISIBLE);

        mlistview.getRefreshableView().addHeaderView(vHeader);
        mlistview.setAdapter(null);

        mBackToTop = mView.findViewById(R.id.back_top);

        mBackToTop.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mlistview.getRefreshableView().setSelection(0);
            }
        });


        super.initViews();
    }

    public void AninationStartStop(final View v, final int y, String type) {
        if (type.equals("up")) {
            Animation transAnimation = new TranslateAnimation(0, 0, 0, v.getMeasuredHeight());
            transAnimation.setDuration(1000);
            v.startAnimation(transAnimation);
            transAnimation.setAnimationListener(new AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {

                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    v.clearAnimation();
                    v.layout(v.getLeft(), -v.getMeasuredHeight(), v.getRight(), 0);
                }
            });
        } else if (type.equals("down")) {
            Animation transAnimation = new TranslateAnimation(0, 0, 0, -v.getMeasuredHeight());
            transAnimation.setDuration(1000);
            v.startAnimation(transAnimation);
            transAnimation.setAnimationListener(new AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {

                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    v.clearAnimation();
                    v.layout(v.getLeft(), 0, v.getRight(), v.getMeasuredHeight());
                }
            });
        }
    }

    boolean flag = true;
    private int mMotionY;

    @SuppressWarnings({"unchecked", "rawtypes"})
    @Override
    protected void initEvents() {
        vDabang.setOnClickListener(this);
        vDaren.setOnClickListener(this);
        vNiuniu.setOnClickListener(this);
        mRightview.setOnClickListener(this);
        mGroupLeft.setOnClickListener(this);
        mGroupRight.setOnClickListener(this);

        mlistview.setOnRefreshListener(new OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                page = 1;
                getBannerData();
                getMainData(page, pagesize, loadFist);
                getHomeGroups();

            }
        });
        mlistview.setOnScrollListener(new OnScrollListener() {

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                    int totalItemCount) {
                if (firstVisibleItem >= 10) {
                    mBackToTop.setVisibility(View.VISIBLE);
                } else {
                    mBackToTop.setVisibility(View.GONE);
                }
                // Animation dowm = AnimationUtils.loadAnimation(mContext, R.anim.home_group_up);
                // // bar 向下的动画
                // Animation up = AnimationUtils.loadAnimation(mContext, R.anim.home_group_down);
                // if (firstVisibleItem > 1) {
                // // vTopFrame.setVisibility(View.GONE);
                // if (vTopbar.getVisibility() == View.VISIBLE) {
                // vTopbar.startAnimation(dowm);
                // mlistview.startAnimation(dowm);
                // vTopbar.setVisibility(View.GONE);
                // }
                //
                // } else {
                // // vTopFrame.setVisibility(View.VISIBLE);
                // if (vTopbar.getVisibility() == View.GONE) {
                // vTopbar.startAnimation(up);
                // mlistview.startAnimation(up);
                // vTopbar.setVisibility(View.VISIBLE);
                // }
                // }

            }
        });


        viewpager.setOnPageChangeListener(new OnPageChangeListener() {
            @Override
            public void onPageSelected(int arg0) {
                currentPage = arg0;
                if (arg0 == 0) {
                    mGroupLeft.setVisibility(View.INVISIBLE);
                } else {
                    mGroupLeft.setVisibility(View.VISIBLE);
                }
                if (groupSize > count * 4) {
                    if (arg0 == count) {
                        mGroupRight.setVisibility(View.INVISIBLE);
                    } else {
                        mGroupRight.setVisibility(View.VISIBLE);
                    }
                } else {
                    if (arg0 == count - 1) {
                        mGroupRight.setVisibility(View.INVISIBLE);
                    } else {
                        mGroupRight.setVisibility(View.VISIBLE);
                    }
                }
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {

            }
        });

        super.initEvents();
    }

    @Override
    protected void loadDatas() {
        getBannerData();
        getMainData(page, pagesize, loadFist);
        getHomeGroups();
        super.loadDatas();
    }

    private void getMainData(int pageN, int pagesizeN, final int loadType) {
        if (CommonUtil.checkNetState(mContext)) {
            getMoccaApi().getMainDatas(String.valueOf(pageN), String.valueOf(pagesizeN),
                    new IRequest<MainDatas>() {
                        @Override
                        public void request(MainDatas t) {
                            mlistview.onRefreshComplete();
                            if (t == null) {

                            } else {
                                if (t.getResult().equals("0")) {
                                    total = Integer.valueOf(t.getTotal());
                                    if (null != t.array && t.array.size() > 0) {
                                        mlistview.setAdapter(new MainAdapter(mContext, t.array,
                                                Constants.PAGE_SIZE, R.layout.main_list_item,
                                                R.layout.item_loading));
                                    }
                                } else {
                                    if (!TextUtils.isEmpty(t.getMsg())) {
                                        Toast.makeText(mContext, t.getMsg(), Toast.LENGTH_SHORT)
                                                .show();
                                    }
                                }
                            }
                        }
                    });
        }

    }

    private class MainAdapter extends XinDaoBaseAdapter<MainData> {

        public MainAdapter(Context context, List<MainData> iniData, int pageSize, int res,
                int loadingRes) {
            super(context, iniData, pageSize, res, loadingRes);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent, final MainData value) {
            ViewHolder holder = (ViewHolder) convertView.getTag();;
            if (holder == null) {
                holder = new ViewHolder();
                holder.content = (TextView) convertView.findViewById(R.id.content);
                holder.pic = (RoundImageView) convertView.findViewById(R.id.pic);
                holder.userface = (CircleImageView) convertView.findViewById(R.id.userface);
                holder.username = (TextView) convertView.findViewById(R.id.username);
                holder.views = (TextView) convertView.findViewById(R.id.views);
                holder.info = (TextView) convertView.findViewById(R.id.info);
                convertView.setTag(holder);
            }
            if (!TextUtils.isEmpty(value.subject)) {
                holder.content.setText(value.subject);
            }
            // CommonParameter.sScreenWidth - CommonUtil.dip2px(mContext, 14),


            int hgt = CommonParameter.sScreenWidth * 320 / 612;
            holder.pic.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, hgt));


            ImageLoader.getInstance().displayImage(value.coverpath, holder.pic);
            ImageLoader.getInstance().displayImage(value.userface, holder.userface);
            holder.username.setText(value.author);
            holder.views.setText(value.views + "访问");
            holder.info.setText(value.replies + "参与");

            convertView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent =
                            new Intent(mContext, com.xindaoapp.happypet.ui.PostDetailActivity.class);
                    intent.putExtra(Constants.KEY_POST_TID, value.tid);
                    intent.putExtra(Constants.KEY_FROM_PAGE, 1);
                    mContext.startActivity(intent);
                }
            });
            return convertView;
        }

        @Override
        public void nextPage(
                int start,
                int size,
                final com.xindaoapp.happypet.adapter.XinDaoBaseAdapter.ILoadNextPageData<MainData> iLoadNextPageData) {
            HappyPetApplication
                    .get()
                    .getMoccaApi()
                    .getMainDatas(String.valueOf(start), String.valueOf(size),
                            new IRequest<MainDatas>() {
                                @Override
                                public void request(MainDatas t) {
                                    if (null != t && t.array != null) {
                                        iLoadNextPageData.loadNextPageData(t.array);
                                    }
                                }
                            });
        }
    }
    private class ViewHolder {
        RoundImageView pic;
        TextView content;
        CircleImageView userface;
        TextView username;
        TextView views;
        TextView info;
    }

    /** 获取广告的数据 */
    private void getBannerData() {
        if (CommonUtil.checkNetState(mContext)) {
            getMoccaApi().getIndexBanner("index", new IRequest<HomeBannerEntity>() {
                @Override
                public void request(HomeBannerEntity t) {
                    mlistview.onRefreshComplete();
                    if (null == t) {
                        if (mFrist) {
                            onDataArrived(false);
                            load_fail.setOnClickListener(new OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    startAnimation();
                                    loadDatas();
                                }
                            });
                        }
                    } else {
                        mFrist = false;
                        onDataArrived(true);
                        if (t.getResult().equals(mResult) && t.getArray().size() > 0) {
                            mBanners = t.getArray();
                            prepareViewPage(mContext, mBanners);
                            // mlistview.getRefreshableView().setAdapter(null);
                        }
                    }
                }
            });
        } else {
            if (mFrist) {
                onDataArrived(false);
                load_fail.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startAnimation();
                        loadDatas();
                    }
                });
            }
            Toast.makeText(mContext, R.string.pLease_check_network, Toast.LENGTH_SHORT).show();
        }
    }

    private ArrayList<View> dotLists;
    private RollViewPager rollViewPager;

    public void prepareViewPage(final Context context, final List<HomeBanner> list) {
        List<String> titleList = new ArrayList<String>();
        List<String> imageUrlList = new ArrayList<String>();
        for (HomeBanner homeBanner : list) {
            titleList.add(homeBanner.getTitle());
            imageUrlList.add(homeBanner.getCoverpath());
        }
        initDots(list.size());
        rollViewPager =
                new RollViewPager(context, dotLists, R.drawable.point_normal,
                        R.drawable.point_enable, new RollViewPager.MyOnTouchCllickCallBack() {
                            @Override
                            public void OnTouchCllick(int position) {
                                String type = list.get(position % list.size()).getType();
                                if (type.equals("web")) {// 跳转到详情
                                    Intent intent1 =
                                            new Intent(context, HomeBannerDetailActivity.class);
                                    intent1.putExtra("url", list.get(position % list.size())
                                            .getLink());
                                    context.startActivity(intent1);
                                    getActivity().overridePendingTransition(
                                            R.anim.new_dync_in_from_right,
                                            R.anim.new_dync_out_to_left);
                                } else if (type.equals("appthread")) {// 跳转到帖子详情
                                    Intent intent2 = new Intent(context, PostDetailActivity.class);
                                    intent2.putExtra(Constants.KEY_POST_TID,
                                            list.get(position % list.size()).getLink());
                                    context.startActivity(intent2);
                                    getActivity().overridePendingTransition(
                                            R.anim.new_dync_in_from_right,
                                            R.anim.new_dync_out_to_left);
                                }
                            }
                        });
        rollViewPager.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                CommonParameter.sScreenWidth * 248 / 640));
        rollViewPager.setTitle(mtvDescription, titleList);
        rollViewPager.setImageUrl(imageUrlList);
        rollViewPager.startRoll();
        mViewPager.removeAllViews();
        mViewPager.addView(rollViewPager);



    }

    private void initDots(int size) {
        dotLists = new ArrayList<View>();
        mllPoints.removeAllViews();
        for (int i = 0; i < size; i++) {
            LinearLayout.LayoutParams layoutParams =
                    new LinearLayout.LayoutParams(CommonUtil.dip2px(mContext, 5),
                            CommonUtil.dip2px(mContext, 5));
            layoutParams.setMargins(5, 0, 5, 0);
            // LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(15,
            // 15);

            // lp.leftMargin = 10;

            ImageView m = new ImageView(mContext);
            // m.setLayoutParams(new LayoutParams(CommonUtil.dip2px(mContext, 3), CommonUtil.dip2px(
            // mContext, 3)));
            if (i == 0) {
                m.setBackgroundResource(R.drawable.point_enable);
            } else {
                m.setBackgroundResource(R.drawable.point_normal);
            }
            m.setLayoutParams(layoutParams);
            dotLists.add(m);
            mllPoints.addView(m);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.niuniu:
                if (UserState.isLogged(getActivity())) {
                    Intent intent = new Intent(mContext, MainActivity.class);
                    intent.putExtra(Constants.KEY_SKIP_CLASS_NAME,
                            ChangeCenterFragment.class.getCanonicalName());
                    mContext.startActivity(intent);
                }
                break;
            case R.id.daren:
                Intent dayen = new Intent(mContext, DayenActivity.class);
                mContext.startActivity(dayen);
                break;
            case R.id.dabang:
                Intent list = new Intent(mContext, ListActivity.class);
                mContext.startActivity(list);
                break;
            case R.id.top_bar_right_imageview:
                Intent search = new Intent(mContext, Search2Activity.class);
                mContext.startActivity(search);
                break;
            case R.id.group_left:
                if (currentPage > 0) {
                    viewpager.setCurrentItem(currentPage - 1);
                }

                break;
            case R.id.group_right:
                if (currentPage < count + 1) {
                    if (groupSize > count * 4) {
                        viewpager.setCurrentItem(currentPage + 1);
                    } else {
                        viewpager.setCurrentItem(currentPage);
                    }
                }
                break;

            default:
                break;
        }
    }

    private List<Group> recommendarray = new ArrayList<Group>();

    private void getHomeGroups() {
        getMoccaApi().getHomeRecommendGroups(new IRequest<Groups>() {
            @Override
            public void request(Groups t) {
                mGroupLeft.setVisibility(View.INVISIBLE);
                mGroupRight.setVisibility(View.VISIBLE);
                mlistview.onRefreshComplete();
                if (null == t) {

                } else {
                    if (t.getResult().equals(mResult)) {
                        if (t.array != null && t.array.size() > 0) {
                            recommendarray.clear();
                            recommendarray = t.array;
                            getRecommentGroups(recommendarray);
                        } else {
                            getRecommentGroups(null);
                        }
                    } else {

                        if (!TextUtils.isEmpty(t.getMsg())) {
                            Toast.makeText(mContext, t.getMsg(), Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            }


        });
    }



    protected void getRecommentGroups(List<Group> recommendarray2) {
        if (recommendarray2.size() > 0) {
            groupSize = recommendarray2.size();
            views.clear();
            int x = recommendarray2.size() / 4;
            count = x;
            for (int i = 0; i < x; i++) {
                List<Group> subList = recommendarray2.subList(i * 4, (i + 1) * 4);
                views.add(new PagerWindow(mContext, subList));
                // List<Group> subList = recommendarray2.subList(i * 4, recommendarray2.size() - 1);
                // views.add(new PagerWindow(mContext, subList));
            }
            List<Group> subList = recommendarray2.subList(x * 4, recommendarray2.size());
            views.add(new PagerWindow(mContext, subList));
            homePagerAdapter = new HomePagerAdapter(views);
            viewpager.setAdapter(homePagerAdapter);
            homePagerAdapter.notifyDataSetChanged();

            // final long downTime = SystemClock.uptimeMillis();
            // final MotionEvent downEvent =
            // MotionEvent.obtain(downTime, downTime, MotionEvent.ACTION_DOWN,
            // viewpager.getLeft(), viewpager.getTop(), 0);
            // final MotionEvent upEvent =
            // MotionEvent.obtain(downTime, SystemClock.uptimeMillis(), MotionEvent.ACTION_UP,
            // 10 + viewpager.getLeft(), viewpager.getTop() + 10, 0);
            // viewpager.onTouchEvent(downEvent);
            // viewpager.onTouchEvent(upEvent);
            // downEvent.recycle();
            // upEvent.recycle();


        }
    }

    private class HomePagerAdapter extends PagerAdapter {
        private final List<PagerWindow> list;

        public HomePagerAdapter(List<PagerWindow> list) {
            super();
            this.list = list;
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return list.size();
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            // TODO Auto-generated method stub
            container.removeView((View) object);
        }

        @Override
        public Object instantiateItem(View container, int position) {
            // TODO Auto-generated method stub
            View view = list.get(position).getView();
            // windows[position].loadData();
            ((ViewGroup) container).addView(view);
            return view;
        }

        @Override
        public boolean isViewFromObject(View view, Object obj) {
            return view == obj;
        }
    }

}
